﻿using DotNetOpenAuth.AspNet;
using DotNetOpenAuth.OpenId.RelyingParty;
using Inovout.Runtime;
using Inovout.Web.Security;
using Microsoft.Web.WebPages.OAuth;
using System.Web.Mvc;
using System.Web.Security;

namespace Inovout.Web.Mvc
{
    public class AccountController : BaseController
    {
        private static OpenIdRelyingParty openIdRelyingParty = new OpenIdRelyingParty();

        static AccountController()
        {
        }
        public AccountController() { }

        [ValidateInput(false)]
        [AllowAnonymous]
        public virtual ActionResult Login(string returnUrl)
        {
            return SignIn(returnUrl);
        }
        [ValidateInput(false)]
        [AllowAnonymous]
        public virtual ActionResult SignIn(string returnUrl)
        {
            //return new AccountAuthenticationResult(InovoutOAuthClient.OAuth2ClientProviderName, Url.Action("SignInCallback", new { ReturnUrl = returnUrl }));
            return new AccountAuthenticationResult(InovoutOpenIdClient.OpenIdProviderName, Url.Action("SignInCallback", new { ReturnUrl = returnUrl }));

        }

        [AllowAnonymous]
        public ActionResult SignInCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("SignInCallback", new { ReturnUrl = returnUrl }));
            if (result.IsSuccessful)
            {
                IFormsAuthenticationService formsAuthenticationService = new FormsAuthenticationService();
                formsAuthenticationService.SignIn(result.ProviderUserId, result.UserName, false);
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return View("SignIn");
                }
            }
            else
            {
                return Signout(returnUrl);
            }
        }

        [AllowAnonymous]
        public ActionResult SignInFailure()
        {
            return View();
        }

        public ActionResult Signout(string returnUrl)
        {
            FormsAuthentication.SignOut();
            string accountSignOut = null;
            if (base.TryGetApplicationSetting("AccountSignOut", out accountSignOut))
            {
                return string.IsNullOrEmpty(returnUrl) ? Redirect(accountSignOut) : Redirect(accountSignOut + "?ReturnUrl=" + returnUrl);
            }
            return string.IsNullOrEmpty(returnUrl) ? Redirect("~/") : Redirect(returnUrl);
        }
        [AllowAnonymous]
        public ActionResult Xrds()
        {
            return View("Xrds");
        }
    }

}